#include "eg.h"
#include <QGraphicsScene>
#include <QPainter>
#include <QStyleOption>
#include <math.h>
#include <QtGui>

static const double Pi = 3.14159265358979323846264338327950288419717;
static double TwoPi = 2.0 * Pi;


Eg::Eg(int Hrun)
{
    x = -200 + qrand()%200;
    y = -200 + qrand()%200;
    setPos (x , y);
    run = Hrun;
    type = 1;
    speed = 0.1;
    mama = NULL;
}

void Eg::paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *)
{

    painter->setBrush(Qt::yellow);
    painter->drawEllipse(-10, -10, 20, 20);

}

void Eg :: rand_position () {
    return;
}

QRectF Eg :: boundingRect() const
{
    qreal adjust = 0.5;
    return QRectF(-11 - adjust, -11 - adjust,
                  21 + adjust, 21 + adjust);
}

void Eg :: advanceNoMama () {
    // Try not to crash with any other Duck

    QList<QGraphicsItem *> dangerDuck = scene()->items(QPolygonF()
                                                       << mapToScene(0, 0)
                                                       << mapToScene(-30, -50)
                                                       << mapToScene(30, -50));
    foreach (QGraphicsItem *item, dangerDuck) {
        if (item == this)
            continue;

        QLineF lineToDuck(QPointF(0, 0), mapFromItem(item, 0, 0));
        qreal angleToDuck = ::acos(lineToDuck.dx() / lineToDuck.length());
        if (lineToDuck.dy() < 0)
            angleToDuck = TwoPi - angleToDuck;
        angleToDuck = (Pi - angleToDuck) + Pi / 2;

        if (angleToDuck >= 0 && angleToDuck < Pi / 2) {
            // Rotate right
            angle += 0.5;
        } else if (angleToDuck <= TwoPi && angleToDuck > (TwoPi - Pi / 2)) {
            // Rotate left
            angle -= 0.5;
        }
    }

    // Add some random movement

    if (dangerDuck.size() > 1 && (qrand() % 10) == 0) {
        if (qrand() % 1)
            angle += (qrand() % 100) / 500.0;
        else
            angle -= (qrand() % 100) / 500.0;
    }

    speed += (-50 + qrand() % 100) / 100.0;

    qreal dx = ::sin(angle) * 10;

    setRotation(rotation() + dx);
    setPos(mapToParent(0, -(3 + sin(speed) * 3)));
}

void Eg::advanceMama() {

}

void Eg::advance(int step) {
    if (!step)
        return;
    if (mama == NULL) advanceNoMama();
    else advanceMama();
}

QPainterPath Eg :: shape() const
{
    QPainterPath path;
    path.addEllipse(-11, -11, 21, 21);
    return path;
}

void Eg :: set_leader (Eg * m) {
    mama = m;
}
